# app/password_mgmt.py

from flask import Blueprint, request, jsonify, session, abort
from .models import User
from . import db

password_bp = Blueprint('password_mgmt', __name__, url_prefix='/api/password')

@password_bp.before_request
def require_login():
    if 'user_id' not in session:
        abort(401)

@password_bp.route('/change', methods=['POST'])
def change_password():
    """
    更改当前登录用户密码：
    POST JSON { "old_password": "...", "new_password": "...", "confirm": "..." }
    """
    data = request.get_json() or {}
    old = data.get('old_password', '').strip()
    new = data.get('new_password', '').strip()
    conf= data.get('confirm', '').strip()

    if not old or not new or not conf:
        return jsonify(error="所有字段均为必填"), 400
    if new != conf:
        return jsonify(error="新密码与确认密码不一致"), 400

    user = User.query.get(session['user_id'])
    if not user.check_password(old):
        return jsonify(error="原密码错误"), 400

    user.set_password(new)
    db.session.commit()
    return jsonify(message="密码修改成功"), 200
